package com.sl.utils.encryptionAlgorithm;

import lombok.extern.slf4j.Slf4j;
import org.apache.axis.encoding.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author ：zhangC
 * @date ：Created in 2020/9/15 14:54
 * @description：AES加解密工具类
 * @version: $2.0
 */
@Slf4j
public class AESUtils {
    private static int Length = 128;
    /**
     * 加密密码
     */
    public static final String strKey = "mingduWMSLicense";
    /**
     * 随机生成的加密密码 每次生成的byte[]却是不同的
     */
    private static byte[] password = generateKey();

    public static void main(String[] args) throws Exception {
        byte[] encrypt = encrypt("2020-09-24 10:02:27");
        String encrypts = encodeBASE64(encrypt);
        log.info(encrypts);
        String decrypt = decrypt(encrypts);
//        String decrypt = decrypt("VTJGc2RHVmtYMTllK2U3RmtSNlliRndyNGtSU3FSN0pySWxlNE9nT1B4K1ppSUFDckxCZVBaMk1DS0xzZXpuTw==");
        log.info(decrypt);
    }
    /**
     * 注意：即便strKey相同 但是每次生成的byte[]却是不同的
     *
     * @param strKey
     * @return 16Byte的加密password
     */
    public static byte[] generateKey() {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            generator.init(Length, secureRandom);
            return generator.generateKey().getEncoded();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.toString());
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content
     * @return
     */
    public static byte[] encrypt(String content) {
        return encrypt(content, strKey);
    }

    /**
     * 加密，传入加密后的密码
     * 解决了出现linux和win系统加解密不一致
     * @param content
     * @return
     */
    public static byte[] encrypt(String content, String secureKey) {
        try {
            if (StringUtils.isEmpty(content)
                    || StringUtils.isEmpty(secureKey)) {
                return null;
            }
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            /* 问题我已自己解决，这个是由于linux和window的内核不同造成的！
             * SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
             * secureRandom.setSeed(PASSWORD.getBytes());
             * 然后初始化，就能解决这个问题！ */
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secureKey.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (Exception e) {
            log.error("加密错误.", e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        return decrypt(content, strKey);
    }

    /**
     * 解密，传入加密后的密码
     * 解决了出现linux和win系统加解密不一致
     * @param content
     * @param strKey
     * @return
     */
    public static String decrypt(String content, String secureKey) {
        try {
            if (StringUtils.isEmpty(content) || StringUtils.isEmpty(secureKey)) {
                return null;
            }
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secureKey.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] base64Dec = Base64.decode(content);
//            byte[] base64Dec = parseHexStr2Byte(content);
            byte[] result = cipher.doFinal(base64Dec);
            return new String(result);
        } catch (Exception e) {
            log.warn("解密错误,错误信息是:{}", e);
        }
        return null;
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 字符串
     * @return 字节数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf 字节数组
     * @return 字符串
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String encodeBASE64(byte[] content) throws Exception {
        if (content == null || content.length == 0)
            return null;
        try {
            return Base64.encode(content);
        } catch (Exception e) {
            log.error("Base64 encode error.", e);
            return null;
        }
    }


}